<?php
/**
 * Created by PhpStorm.
 * User: yuyj
 * Date: 2016-03-16
 * Time: 19:11
 */

namespace common\repositories\common;

use common\entities\common\MyscrmXunjianDatabaseEntity;
use common\repositories\BaseRepository;
use common\support\StringHelper;
use Yii;
use yii\helpers\Json;

class MyscrmXunjianDatabaseRepository extends BaseRepository
{
    public $entity;

    public function __construct(MyscrmXunjianDatabaseEntity $entity, $config = [])
    {
        $this->entity = $entity;

        return parent::__construct($config);
    }

    /**
     * @param $orgCode
     * @return MyscrmXunjianDatabaseEntity
     */
    public function getDatabaseInstance($orgCode)
    {
        return $this->entity->find()->where(
            ['org_code' => $orgCode]
        )->one();
    }

    /**
     * @param $orgCode
     * @param $databaseInstanceId
     * @return bool|MyscrmXunjianDatabaseEntity
     */
    public function assignDatabaseInstance($orgCode, $databaseInstanceId, $databaseName)
    {
        $model = $this->getDatabaseInstance($orgCode);

        if (!$model) {
            $model = new MyscrmXunjianDatabaseEntity;
            $model->id = StringHelper::uuid();
            $model->org_code = $orgCode;
        }

        $model->database_name = $databaseName;
        $model->database_instance_id = $databaseInstanceId;

        if ($model->save()) {
            return $model->id;
        } else {
            Yii::error(Json::encode($model->getErrors()));

            return false;
        }
    }

    public function deleteDatabaseInstance($orgCode)
    {
        return $this->entity->deleteAll(
            [
                'org_code' => $orgCode,
            ]
        );
    }
}
